package com.sali.utils.loadbalance;

import com.sali.utils.loadbalance.entity.RequestId;
import org.springframework.cloud.client.ServiceInstance;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * @description: 加权轮询算法
 * @author: zhang hang
 * @date: 2022/7/18 21:00.
 * @version: 1.0
 */
public class WeightedRoundRobin implements ILoadBalanceAlgorithm {

    public static final Map<Integer, Integer> WEIGHT_MAP = new LinkedHashMap<>();

    static {
        WEIGHT_MAP.put(8861, 1);
        WEIGHT_MAP.put(8862, 2);
        WEIGHT_MAP.put(8863, 3);
        WEIGHT_MAP.put(8864, 4);
        WEIGHT_MAP.put(8865, 5);
    }

    @Override
    public ServiceInstance algorithmDetail(List<ServiceInstance> instances) {

        int totalWeight = 0;
        for (Integer weight : WEIGHT_MAP.values()) {
            totalWeight += weight;
        }

        Integer requestId = RequestId.getAndIncrement();
        int offset = requestId % totalWeight;

        for (Integer port : WEIGHT_MAP.keySet()) {
            Integer weight = WEIGHT_MAP.get(port);
            if (offset < weight) {
                for (ServiceInstance instance : instances) {
                    if (instance.getPort() == port) {
                        return instance;
                    }
                }
            }
            offset = offset - weight;
        }
        return null;
    }

}

